<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class CategoryPost extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [];

        if ($this->has('id') || $this->isMethod('patch') || $this->isMethod('put')) { // 账户信息修改
            $this->rulesForUpdate($rules);
        } else {
            $this->rulesForAdd($rules);
        }
        return $rules;
    }

    private function rulesForAdd(&$rules)
    {
        $rules['parent_id'] = 'required';

        $rules['code'] = [
            'required',
            Rule::unique('categories')
        ];

        $rules['name'] = [
            'required',
            'min:2',
            'max:20',
            Rule::unique('categories')
        ];
    }

    private function rulesForUpdate(&$rules)
    {
        $rules['parent_id'] = 'required';

        $rules['code'] = [
            'required',
            Rule::unique('categories')->ignore($this->id)
        ];
        $rules['name'] = [
            'required',
            'min:2',
            'max:20',
            Rule::unique('categories')->ignore($this->id)
        ];
    }

    public function attributes()
    {
        return [
            'code' => '分类标识',
            'name' => '分类',
            'sort' => '排序字段'
        ];
    }
}
